﻿// --------------------------------
// <copyright file="SpinLock.cs" company="Faculty of Information Technology, Czech Technical University in Prague">
//     This document is shared by Microsoft Public License (MS-PL)
//     For further details please see http://msdn.microsoft.com/en-us/library/ff648068.aspx or license.txt.
// </copyright>
// <author>Lukáš Molnár</author>

// <email>molnaluk@fit.cvut.cz</email>

// <date>4. 4. 2012 11:20:12</date>

// <summary>
// 
// </summary>
// --------------------------------

using System;
using System.Threading;

namespace FITClub.Util  
{
    /// <summary>
    /// The fastest possible implementation of thread synchronization technique.
    /// </summary>
    public class SpinLock
    {
        private TimeSpan waitInterval;
        private volatile bool locked;

        public long WaitTicks
        {
            get { return this.waitInterval.Ticks; }
            set { this.waitInterval = TimeSpan.FromTicks(value); }
        }

        public SpinLock(long ticks)
        {
            this.WaitTicks = ticks;
            locked = false;
        }

        /// <summary>
        /// Locks current thread
        /// </summary>
        public void Lock()
        {
            while (locked) Thread.Sleep(waitInterval);
            locked = true;
        }

        /// <summary>
        /// Unlocks access.
        /// </summary>
        public void Unlock()
        {
            this.locked = false;
        }
    }
}
